home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / pcl / src-16f.lha / code / macros.lisp < prev    next >
Encoding:
Text File  |  1992-12-09  |  58.5 KB  |  1,704 lines

  1. ;;; -*- Log: code.log; Package: Lisp -*-
  2. ;;;
  3. ;;; **********************************************************************
  4. ;;; This code was written as part of the CMU Common Lisp project at
  5. ;;; Carnegie Mellon University, and has been placed in the public domain.
  6. ;;; If you want to use this code or any part of CMU Common Lisp, please contact
  7. ;;; Scott Fahlman or slisp-group@cs.cmu.edu.
  8. ;;;
  9. (ext:file-comment
  10.   "$Header: macros.lisp,v 1.35 92/09/01 17:41:52 ram Exp $")
  11. ;;;
  12. ;;; **********************************************************************
  13. ;;;
  14. ;;; This file contains the macros that are part of the standard
  15. ;;; Spice Lisp environment.
  16. ;;;
  17. ;;; Written by Scott Fahlman and Rob MacLachlan.
  18. ;;; Modified by Bill Chiles to adhere to the wall.
  19. ;;;
  20. (in-package "LISP")
  21. (export '(defvar defparameter defconstant when unless setf
  22.       defsetf define-setf-method psetf shiftf rotatef push pushnew pop
  23.       incf decf remf case typecase with-open-file
  24.       with-open-stream with-input-from-string with-output-to-string
  25.       locally etypecase ctypecase ecase ccase
  26.       get-setf-method get-setf-method-multiple-value
  27.           define-modify-macro destructuring-bind nth-value
  28.           otherwise ; Sacred to CASE and related macros.
  29.       define-compiler-macro))
  30.  
  31. (in-package "EXTENSIONS")
  32. (export '(do-anonymous collect iterate))
  33.  
  34. (in-package "LISP")
  35.  
  36.  
  37. ;;; Parse-Body  --  Public
  38. ;;;
  39. ;;;    Parse out declarations and doc strings, *not* expanding macros.
  40. ;;; Eventually the environment arg should be flushed, since macros can't expand
  41. ;;; into declarations anymore.
  42. ;;;
  43. (defun parse-body (body environment &optional (doc-string-allowed t))
  44.   "This function is to parse the declarations and doc-string out of the body of
  45.   a defun-like form.  Body is the list of stuff which is to be parsed.
  46.   Environment is ignored.  If Doc-String-Allowed is true, then a doc string
  47.   will be parsed out of the body and returned.  If it is false then a string
  48.   will terminate the search for declarations.  Three values are returned: the
  49.   tail of Body after the declarations and doc strings, a list of declare forms,
  50.   and the doc-string, or NIL if none."
  51.   (declare (ignore environment))
  52.   (let ((decls ())
  53.     (doc nil))
  54.     (do ((tail body (cdr tail)))
  55.     ((endp tail)
  56.      (values tail (nreverse decls) doc))
  57.       (let ((form (car tail)))
  58.     (cond ((and (stringp form) (cdr tail))
  59.            (if doc-string-allowed
  60.            (setq doc form)
  61.            (return (values tail (nreverse decls) doc))))
  62.           ((not (and (consp form) (symbolp (car form))))
  63.            (return (values tail (nreverse decls) doc)))
  64.           ((eq (car form) 'declare)
  65.            (push form decls))
  66.           (t
  67.            (return (values tail (nreverse decls) doc))))))))
  68.  
  69.  
  70. ;;;; DEFMACRO:
  71.  
  72. ;;; Defmacro  --  Public
  73. ;;;
  74. ;;;    Parse the definition and make an expander function.  The actual
  75. ;;; definition is done by %defmacro which we expand into.
  76. ;;;
  77. (defmacro defmacro (name lambda-list &body body)
  78.   (let ((whole (gensym "WHOLE-"))
  79.     (environment (gensym "ENV-")))
  80.     (multiple-value-bind
  81.     (body local-decs doc)
  82.     (parse-defmacro lambda-list whole body name 'defmacro
  83.             :environment environment)
  84.       (let ((def `(lambda (,whole ,environment)
  85.             ,@local-decs
  86.             (block ,name
  87.               ,body))))
  88.     `(c::%defmacro ',name #',def ',lambda-list ,doc)))))
  89.  
  90.  
  91. ;;; %Defmacro, %%Defmacro  --  Internal
  92. ;;;
  93. ;;;    Defmacro expands into %Defmacro which is a function that is treated
  94. ;;; magically the compiler.  After the compiler has gotten the information it
  95. ;;; wants out of macro definition, it compiles a call to %%Defmacro which
  96. ;;; happens at load time.  We have a %Defmacro function which just calls
  97. ;;; %%Defmacro in order to keep the interpreter happy.
  98. ;;;
  99. ;;;    Eventually %%Defmacro should deal with clearing old compiler information
  100. ;;; for the functional value.
  101. ;;;
  102. (defun c::%defmacro (name definition lambda-list doc)
  103.   (assert (eval:interpreted-function-p definition))
  104.   (setf (eval:interpreted-function-name definition)
  105.     (format nil "DEFMACRO ~S" name))
  106.   (setf (eval:interpreted-function-arglist definition) lambda-list)
  107.   (c::%%defmacro name definition doc))
  108. ;;;
  109. (defun c::%%defmacro (name definition doc)
  110.   (clear-info function where-from name)
  111.   (setf (macro-function name) definition)
  112.   (setf (documentation name 'function) doc)
  113.   name)
  114.  
  115.  
  116.  
  117. ;;;; DEFINE-COMPILER-MACRO
  118.  
  119. (defmacro define-compiler-macro (name lambda-list &body body)
  120.   "Define a compiler-macro for NAME."
  121.   (let ((whole (gensym "WHOLE-"))
  122.     (environment (gensym "ENV-")))
  123.     (multiple-value-bind
  124.     (body local-decs doc)
  125.     (parse-defmacro lambda-list whole body name 'define-compiler-macro
  126.             :environment environment)
  127.       (let ((def `(lambda (,whole ,environment)
  128.             ,@local-decs
  129.             (block ,name
  130.               ,body))))
  131.     `(c::%define-compiler-macro ',name #',def ',lambda-list ,doc)))))
  132.  
  133. (defun c::%define-compiler-macro (name definition lambda-list doc)
  134.   (assert (eval:interpreted-function-p definition))
  135.   (setf (eval:interpreted-function-name definition)
  136.     (let ((*print-case* :upcase))
  137.       (format nil "DEFINE-COMPILER-MACRO ~S" name)))
  138.   (setf (eval:interpreted-function-arglist definition) lambda-list)
  139.   (c::%%define-compiler-macro name definition doc))
  140. ;;;
  141. (defun c::%%define-compiler-macro (name definition doc)
  142.   (setf (compiler-macro-function name) definition)
  143.   (setf (documentation name 'compiler-macro) doc)
  144.   name)
  145.  
  146.  
  147.  
  148. ;;; DEFTYPE is a lot like DEFMACRO.
  149.  
  150. (defmacro deftype (name arglist &body body)
  151.   "Syntax like DEFMACRO, but defines a new type."
  152.   (unless (symbolp name)
  153.     (error "~S -- Type name not a symbol." name))
  154.   
  155.   (let ((whole (gensym "WHOLE-")))
  156.     (multiple-value-bind (body local-decs doc)
  157.              (parse-defmacro arglist whole body name 'deftype
  158.                      :default-default ''*)
  159.       `(eval-when (compile load eval)
  160.      (%deftype ',name
  161.            #'(lambda (,whole)
  162.                ,@local-decs
  163.                (block ,name ,body))
  164.            ,@(when doc `(,doc)))))))
  165. ;;;
  166. (defun %deftype (name expander &optional doc)
  167.   (ecase (info type kind name)
  168.     (:primitive
  169.      (error "Illegal to redefine standard type: ~S." name))
  170.     (:structure
  171.      (warn "Redefining structure type ~S with DEFTYPE." name)
  172.      (c::undefine-structure (info type structure-info name)))
  173.     ((nil :defined)))
  174.   (setf (info type kind name) :defined)
  175.   (setf (info type expander name) expander)
  176.   (when doc
  177.     (setf (documentation name 'type) doc))
  178.   ;; ### Bootstrap hack -- we need to define types before %note-type-defined
  179.   ;; is defined.
  180.   (when (fboundp 'c::%note-type-defined)
  181.     (c::%note-type-defined name))
  182.   name)
  183.  
  184.  
  185. ;;; And so is DEFINE-SETF-METHOD.
  186.  
  187. (defparameter defsetf-error-string "Setf expander for ~S cannot be called with ~S args.")
  188.  
  189. (defmacro define-setf-method (access-fn lambda-list &body body)
  190.   "Syntax like DEFMACRO, but creates a Setf-Method generator.  The body
  191.   must be a form that returns the five magical values."
  192.   (unless (symbolp access-fn)
  193.     (error "~S -- Access-function name not a symbol in DEFINE-SETF-METHOD."
  194.        access-fn))
  195.  
  196.   (let ((whole (gensym "WHOLE-"))
  197.     (environment (gensym "ENV-")))
  198.     (multiple-value-bind (body local-decs doc)
  199.              (parse-defmacro lambda-list whole body access-fn
  200.                      'define-setf-method
  201.                      :environment environment)
  202.       `(eval-when (load compile eval)
  203.      (%define-setf-macro
  204.       ',access-fn
  205.       #'(lambda (,whole ,environment)
  206.           ,@local-decs
  207.           (block ,access-fn ,body))
  208.       nil
  209.       ',doc)))))
  210.  
  211.  
  212. ;;; %DEFINE-SETF-MACRO  --  Internal
  213. ;;;
  214. ;;;    Do stuff for defining a setf macro.
  215. ;;;
  216. (defun %define-setf-macro (name expander inverse doc)
  217.   (cond ((not (fboundp `(setf ,name))))
  218.     ((info function accessor-for name)
  219.      (warn "Defining setf macro for destruct slot accessor; redefining as ~
  220.             a normal function:~%  ~S"
  221.            name)
  222.      (c::define-function-name name))
  223.     ((not (eq (symbol-package name) (symbol-package 'aref)))
  224.      (warn "Defining setf macro for ~S, but ~S is fbound."
  225.            name `(setf ,name))))
  226.   (when (or inverse (info setf inverse name))
  227.     (setf (info setf inverse name) inverse))
  228.   (when (or expander (info setf expander name))
  229.     (setf (info setf expander name) expander))
  230.   (when doc
  231.     (setf (documentation name 'setf) doc))
  232.   name)
  233.   
  234.  
  235. ;;;; Destructuring-bind
  236.  
  237. (defmacro destructuring-bind (lambda-list arg-list &rest body)
  238.   "Bind the variables in LAMBDA-LIST to the contents of ARG-LIST."
  239.   (let* ((arg-list-name (gensym "ARG-LIST-")))
  240.     (multiple-value-bind
  241.     (body local-decls)
  242.     (parse-defmacro lambda-list arg-list-name body nil 'destructuring-bind
  243.             :annonymousp t :doc-string-allowed nil)
  244.       `(let ((,arg-list-name ,arg-list))
  245.      ,@local-decls
  246.      ,body))))
  247.  
  248.  
  249. ;;;; Defun, Defvar, Defparameter, Defconstant:
  250.  
  251. ;;; Defun  --  Public
  252. ;;;
  253. ;;;    Very similar to Defmacro, but simpler.  We don't have to parse the
  254. ;;; lambda-list.
  255. ;;;
  256. (defmacro defun (&whole source name lambda-list &body (body decls doc))
  257.   (let ((def `(lambda ,lambda-list
  258.         ,@decls
  259.         (block ,(if (and (consp name) (eq (car name) 'setf))
  260.                 (cadr name)
  261.                 name)
  262.           ,@body))))
  263.     `(c::%defun ',name #',def ,doc ',source)))
  264.  
  265.  
  266. ;;; %Defun, %%Defun  --  Internal
  267. ;;;
  268. ;;;    Similar to %Defmacro, ...
  269. ;;;
  270. (defun c::%%defun (name def doc &optional inline-expansion)
  271.   (setf (fdefinition name) def)
  272.   (when doc
  273.     (if (and (consp name) (eq (first name) 'setf))
  274.     (setf (documentation (second name) 'setf) doc)
  275.     (setf (documentation name 'function) doc)))
  276.   (c::define-function-name name)
  277.   (when (eq (info function where-from name) :assumed)
  278.     (setf (info function where-from name) :defined)
  279.     (when (info function assumed-type name)
  280.       (setf (info function assumed-type name) nil)))
  281.   (when (or inline-expansion
  282.         (info function inline-expansion name))
  283.     (setf (info function inline-expansion name) inline-expansion))
  284.   name)
  285. ;;;
  286. (defun c::%defun (name def doc source)
  287.   (declare (ignore source))
  288.   (assert (eval:interpreted-function-p def))
  289.   (setf (eval:interpreted-function-name def) name)
  290.   (c::%%defun name def doc))
  291.  
  292.  
  293. ;;; DEFCONSTANT  --  Public
  294. ;;;
  295. (defmacro defconstant (var val &optional doc)
  296.   "For defining global constants at top level.  The DEFCONSTANT says that the
  297.   value is constant and may be compiled into code.  If the variable already has
  298.   a value, and this is not equal to the init, an error is signalled.  The third
  299.   argument is an optional documentation string for the variable."
  300.   `(c::%defconstant ',var ,val ',doc))
  301.  
  302. ;;; %Defconstant, %%Defconstant  --  Internal
  303. ;;;
  304. ;;;    Like the other %mumbles except that we currently actually do something
  305. ;;; interesting at load time, namely checking if the constant is being
  306. ;;; redefined.
  307. ;;;
  308. (defun c::%defconstant (name value doc)
  309.   (c::%%defconstant name value doc))
  310. ;;;
  311. (defun c::%%defconstant (name value doc)
  312.   (when doc
  313.     (setf (documentation name 'variable) doc))
  314.   (when (boundp name)
  315.     (unless (equalp (symbol-value name) value)
  316.       (cerror "Go ahead and change the value."
  317.           "Constant ~S being redefined." name)))
  318.   (setf (symbol-value name) value)
  319.   (setf (info variable kind name) :constant)
  320.   (clear-info variable constant-value name)
  321.   name)
  322.  
  323.  
  324. (defmacro defvar (var &optional (val nil valp) (doc nil docp))
  325.   "For defining global variables at top level.  Declares the variable
  326.   SPECIAL and, optionally, initializes it.  If the variable already has a
  327.   value, the old value is not clobbered.  The third argument is an optional
  328.   documentation string for the variable."
  329.   `(progn
  330.     (proclaim '(special ,var))
  331.      ,@(when valp
  332.      `((unless (boundp ',var)
  333.          (setq ,var ,val))))
  334.     ,@(when docp
  335.     `((setf (documentation ',var 'variable) ',doc)))
  336.     ',var))
  337.  
  338. (defmacro defparameter (var val &optional (doc nil docp))
  339.   "Defines a parameter that is not normally changed by the program,
  340.   but that may be changed without causing an error.  Declares the
  341.   variable special and sets its value to VAL.  The third argument is
  342.   an optional documentation string for the parameter."
  343.   `(progn
  344.     (proclaim '(special ,var))
  345.     (setq ,var ,val)
  346.     ,@(when docp
  347.     `((setf (documentation ',var 'variable) ',doc)))
  348.     ',var))
  349.  
  350.  
  351. ;;;; ASSORTED CONTROL STRUCTURES
  352.  
  353.  
  354. (defmacro when (test &body forms)
  355.   "First arg is a predicate.  If it is non-null, the rest of the forms are
  356.   evaluated as a PROGN."
  357.   `(cond (,test nil ,@forms)))
  358.  
  359. (defmacro unless (test &rest forms)
  360.   "First arg is a predicate.  If it is null, the rest of the forms are
  361.   evaluated as a PROGN."
  362.   `(cond ((not ,test) nil ,@forms)))
  363.  
  364.  
  365. (defmacro return (&optional (value nil))
  366.   `(return-from nil ,value))
  367.  
  368. (defmacro prog (varlist &body (body decls))
  369.   `(block nil
  370.      (let ,varlist
  371.        ,@decls
  372.        (tagbody ,@body))))
  373.  
  374. (defmacro prog* (varlist &body (body decls))
  375.   `(block nil
  376.      (let* ,varlist
  377.        ,@decls
  378.        (tagbody ,@body))))
  379.  
  380.  
  381. ;;; Prog1, Prog2  --  Public
  382. ;;;
  383. ;;;    These just turn into a Let.
  384. ;;;
  385. (defmacro prog1 (result &rest body)
  386.   (let ((n-result (gensym)))
  387.     `(let ((,n-result ,result))
  388.        ,@body
  389.        ,n-result)))
  390. ;;;
  391. (defmacro prog2 (form1 result &rest body)
  392.   `(prog1 (progn ,form1 ,result) ,@body))
  393.  
  394.  
  395. ;;; And, Or  --  Public
  396. ;;;
  397. ;;;    AND and OR are defined in terms of IF.
  398. ;;;
  399. (defmacro and (&rest forms)
  400.   (cond ((endp forms) t)
  401.     ((endp (rest forms)) (first forms))
  402.     (t
  403.      `(if ,(first forms)
  404.           (and ,@(rest forms))
  405.           nil))))
  406. ;;;
  407. (defmacro or (&rest forms)
  408.   (cond ((endp forms) nil)
  409.     ((endp (rest forms)) (first forms))
  410.     (t
  411.      (let ((n-result (gensym)))
  412.        `(let ((,n-result ,(first forms)))
  413.           (if ,n-result
  414.           ,n-result
  415.           (or ,@(rest forms))))))))
  416.  
  417.  
  418. ;;; Cond  --  Public
  419. ;;;
  420. ;;;    COND also turns into IF.
  421. ;;;
  422. (defmacro cond (&rest clauses)
  423.   (if (endp clauses)
  424.       nil
  425.       (let ((clause (first clauses)))
  426.     (when (atom clause)
  427.       (error "Cond clause is not a list: ~S." clause))
  428.     (let ((test (first clause))
  429.           (forms (rest clause)))
  430.       (if (endp forms)
  431.           (let ((n-result (gensym)))
  432.         `(let ((,n-result ,test))
  433.            (if ,n-result
  434.                ,n-result
  435.                (cond ,@(rest clauses)))))
  436.           `(if ,test
  437.            (progn ,@forms)
  438.            (cond ,@(rest clauses))))))))
  439.  
  440.  
  441. ;;;; Multiple value macros:
  442.  
  443. ;;; Multiple-Value-XXX  --  Public
  444. ;;;
  445. ;;;    All the multiple-value receiving forms are defined in terms of
  446. ;;; Multiple-Value-Call.
  447. ;;;
  448. (defmacro multiple-value-setq (varlist value-form)
  449.   (unless (and (listp varlist) (every #'symbolp varlist))
  450.     (error "Varlist is not a list of symbols: ~S." varlist))
  451.   (let ((temps (mapcar #'(lambda (x) (declare (ignore x)) (gensym)) varlist)))
  452.     `(multiple-value-bind ,temps ,value-form
  453.        ,@(mapcar #'(lambda (var temp)
  454.              `(setq ,var ,temp))
  455.          varlist temps)
  456.        ,(car temps))))
  457. ;;;
  458. (defmacro multiple-value-bind (varlist value-form &body body)
  459.   (unless (and (listp varlist) (every #'symbolp varlist))
  460.     (error "Varlist is not a list of symbols: ~S." varlist))
  461.   (if (= (length varlist) 1)
  462.       `(let ((,(car varlist) ,value-form))
  463.      ,@body)
  464.       (let ((ignore (gensym)))
  465.     `(multiple-value-call #'(lambda (&optional ,@varlist &rest ,ignore)
  466.                   (declare (ignore ,ignore))
  467.                   ,@body)
  468.        ,value-form))))
  469. ;;;
  470. (defmacro multiple-value-list (value-form)
  471.   `(multiple-value-call #'list ,value-form))
  472.  
  473.  
  474. (defmacro nth-value (n form)
  475.   "Evaluates FORM and returns the Nth value (zero based).  This involves no
  476.   consing when N is a trivial constant integer."
  477.   (if (integerp n)
  478.       (let ((dummy-list nil)
  479.             (keeper (gensym "KEEPER-")))
  480.         ;; We build DUMMY-LIST, a list of variables to bind to useless
  481.         ;; values, then we explicitly IGNORE those bindings and return
  482.         ;; KEEPER, the only thing we're really interested in right now.
  483.         (dotimes (i n)
  484.           (push (gensym "IGNORE-") dummy-list))
  485.         `(multiple-value-bind (,@dummy-list ,keeper)
  486.                               ,form
  487.            (declare (ignore ,@dummy-list))
  488.            ,keeper))
  489.       (once-only ((n n))
  490.     `(case (the fixnum ,n)
  491.        (0 (nth-value 0 ,form))
  492.        (1 (nth-value 1 ,form))
  493.        (2 (nth-value 2 ,form))
  494.        (T (nth (the fixnum ,n) (multiple-value-list ,form)))))))
  495.  
  496.  
  497. ;;;; SETF and friends.
  498.  
  499. ;;; Note: The expansions for SETF and friends sometimes create needless
  500. ;;; LET-bindings of argument values.  The compiler will remove most of
  501. ;;; these spurious bindings, so SETF doesn't worry too much about creating
  502. ;;; them. 
  503.  
  504. ;;; The inverse for a generalized-variable reference function is stored in
  505. ;;; one of two ways:
  506. ;;;
  507. ;;; A SETF-INVERSE property corresponds to the short form of DEFSETF.  It is
  508. ;;; the name of a function takes the same args as the reference form, plus a
  509. ;;; new-value arg at the end.
  510. ;;;
  511. ;;; A SETF-METHOD-EXPANDER property is created by the long form of DEFSETF or
  512. ;;; by DEFINE-SETF-METHOD.  It is a function that is called on the reference
  513. ;;; form and that produces five values: a list of temporary variables, a list
  514. ;;; of value forms, a list of the single store-value form, a storing function,
  515. ;;; and an accessing function.
  516.  
  517. (defun get-setf-method-multiple-value (form &optional environment)
  518.   "Returns five values needed by the SETF machinery: a list of temporary
  519.    variables, a list of values with which to fill them, a list of temporaries
  520.    for the new values, the setting function, and the accessing function."
  521.   (let (temp)
  522.     (cond ((symbolp form)
  523.        (multiple-value-bind
  524.            (expansion expanded)
  525.            (macroexpand-1 form environment)
  526.          (if expanded
  527.          (get-setf-method-multiple-value expansion)
  528.          (let ((new-var (gensym)))
  529.            (values nil nil (list new-var)
  530.                `(setq ,form ,new-var) form)))))
  531.       ;;
  532.       ;; Local functions inhibit global setf methods...
  533.       ((and environment
  534.         (c::leaf-p (cdr (assoc (car form)
  535.                        (c::lexenv-functions environment)))))
  536.        (get-setf-method-inverse form `(funcall #'(setf ,(car form))) t))
  537.       ((setq temp (info setf inverse (car form)))
  538.        (get-setf-method-inverse form `(,temp) nil))
  539.       ((setq temp (info setf expander (car form)))
  540.        (funcall temp form environment))
  541.       ;;
  542.       ;; If a macro, expand one level and try again.  If not, go for the
  543.       ;; SETF function.
  544.       (t
  545.        (multiple-value-bind (res win)
  546.                 (macroexpand-1 form environment)
  547.          (if win
  548.          (get-setf-method res environment)
  549.          (get-setf-method-inverse form
  550.                       `(funcall #'(setf ,(car form)))
  551.                       t)))))))
  552.  
  553. (defun get-setf-method-inverse (form inverse setf-function)
  554.   (let ((new-var (gensym))
  555.     (vars nil)
  556.     (vals nil))
  557.     (dolist (x (cdr form))
  558.       (push (gensym) vars)
  559.       (push x vals))
  560.     (setq vals (nreverse vals))
  561.     (values vars vals (list new-var)
  562.         (if setf-function
  563.         `(,@inverse ,new-var ,@vars)
  564.         `(,@inverse ,@vars ,new-var))
  565.         `(,(car form) ,@vars))))
  566.  
  567.  
  568. (defun get-setf-method (form &optional environment)
  569.   "Like Get-Setf-Method-Multiple-Value, but signal an error if there are
  570.    more than one new-value variables."
  571.   (multiple-value-bind
  572.       (temps value-forms store-vars store-form access-form)
  573.       (get-setf-method-multiple-value form environment)
  574.     (when (cdr store-vars)
  575.       (error "GET-SETF-METHOD used for a form with multiple store ~
  576.           variables:~%  ~S" form))
  577.     (values temps value-forms store-vars store-form access-form)))
  578.  
  579.  
  580. (defun defsetter (fn rest)
  581.   (let ((arglist (car rest))
  582.     (arglist-var (gensym "ARGS-"))
  583.     (new-var (car (cadr rest))))
  584.     (multiple-value-bind
  585.     (body local-decs doc)
  586.     (parse-defmacro arglist arglist-var (cddr rest) fn 'defsetf)
  587.       (values 
  588.        `(lambda (,arglist-var ,new-var)
  589.       ,@local-decs
  590.       ,body)
  591.        doc))))
  592.  
  593.  
  594. (defmacro defsetf (access-fn &rest rest)
  595.   "Associates a SETF update function or macro with the specified access
  596.   function or macro.  The format is complex.  See the manual for
  597.   details."
  598.   (cond ((not (listp (car rest)))
  599.      `(eval-when (load compile eval)
  600.         (%define-setf-macro ',access-fn nil ',(car rest)
  601.                 ,(when (and (car rest) (stringp (cadr rest)))
  602.                    `',(cadr rest)))))
  603.     ((and (cdr rest) (listp (cadr rest)))
  604.      (destructuring-bind
  605.          (lambda-list (&rest store-variables) &body body)
  606.          rest
  607.        (let ((arglist-var (gensym "ARGS-"))
  608.          (access-form-var (gensym "ACCESS-FORM-"))
  609.          (env-var (gensym "ENVIRONMENT-")))
  610.          (multiple-value-bind
  611.          (body local-decs doc)
  612.          (parse-defmacro `(,lambda-list ,@store-variables)
  613.                  arglist-var body access-fn 'defsetf
  614.                  :annonymousp t)
  615.            `(eval-when (load compile eval)
  616.           (%define-setf-macro
  617.            ',access-fn
  618.            #'(lambda (,access-form-var ,env-var)
  619.                (declare (ignore ,env-var))
  620.                (%defsetf ,access-form-var ,(length store-variables)
  621.                  #'(lambda (,arglist-var)
  622.                      ,@local-decs
  623.                      (block ,access-fn
  624.                        ,body))))
  625.            nil
  626.            ',doc))))))
  627.     (t
  628.      (error "Ill-formed DEFSETF for ~S." access-fn))))
  629.  
  630. (defun %defsetf (orig-access-form num-store-vars expander)
  631.   (collect ((subforms) (subform-vars) (subform-exprs) (store-vars))
  632.     (dolist (subform (cdr orig-access-form))
  633.       (if (constantp subform)
  634.       (subforms subform)
  635.       (let ((var (gensym)))
  636.         (subforms var)
  637.         (subform-vars var)
  638.         (subform-exprs subform))))
  639.     (dotimes (i num-store-vars)
  640.       (store-vars (gensym)))
  641.     (values (subform-vars)
  642.         (subform-exprs)
  643.         (store-vars)
  644.         (funcall expander (cons (subforms) (store-vars)))
  645.         `(,(car orig-access-form) ,@(subforms)))))
  646.  
  647.  
  648. ;;; SETF  --  Public
  649. ;;;
  650. ;;;    Except for atoms, we always call GET-SETF-METHOD, since it has some
  651. ;;; non-trivial semantics.  But when there is a setf inverse, and G-S-M uses
  652. ;;; it, then we return a call to the inverse, rather than returning a hairy let
  653. ;;; form.  This is probably important mainly as a convenince in allowing the
  654. ;;; use of setf inverses without the full interpreter.
  655. ;;;
  656. (defmacro setf (&rest args &environment env)
  657.   "Takes pairs of arguments like SETQ.  The first is a place and the second
  658.   is the value that is supposed to go into that place.  Returns the last
  659.   value.  The place argument may be any of the access forms for which SETF
  660.   knows a corresponding setting form."
  661.   (let ((nargs (length args)))
  662.     (cond
  663.      ((= nargs 2)
  664.       (let ((place (first args))
  665.         (value-form (second args)))
  666.     (if (atom place)
  667.         `(setq ,place ,value-form)
  668.         (multiple-value-bind (dummies vals newval setter getter)
  669.                  (get-setf-method-multiple-value place env)
  670.           (declare (ignore getter))
  671.           (let ((inverse (info setf inverse (car place))))
  672.         (if (and inverse (eq inverse (car setter)))
  673.             `(,inverse ,@(cdr place) ,value-form)
  674.             `(let* (,@(mapcar #'list dummies vals))
  675.                (multiple-value-bind ,newval ,value-form
  676.              ,setter))))))))
  677.      ((oddp nargs) 
  678.       (error "Odd number of args to SETF."))
  679.      (t
  680.       (do ((a args (cddr a)) (l nil))
  681.       ((null a) `(progn ,@(nreverse l)))
  682.     (setq l (cons (list 'setf (car a) (cadr a)) l)))))))
  683.  
  684. (defmacro psetf (&rest args &environment env)
  685.   "This is to SETF as PSETQ is to SETQ.  Args are alternating place
  686.   expressions and values to go into those places.  All of the subforms and
  687.   values are determined, left to right, and only then are the locations
  688.   updated.  Returns NIL."
  689.   (collect ((let*-bindings) (mv-bindings) (setters))
  690.     (do ((a args (cddr a)))
  691.     ((endp a))
  692.       (if (endp (cdr a))
  693.       (error "Odd number of args to PSETF."))
  694.       (multiple-value-bind
  695.       (dummies vals newval setter getter)
  696.       (get-setf-method-multiple-value (car a) env)
  697.     (declare (ignore getter))
  698.     (let*-bindings (mapcar #'list dummies vals))
  699.     (mv-bindings (list newval (cadr a)))
  700.     (setters setter)))
  701.     (labels ((thunk (let*-bindings mv-bindings)
  702.            (if let*-bindings
  703.            `(let* ,(car let*-bindings)
  704.               (multiple-value-bind ,@(car mv-bindings)
  705.             ,(thunk (cdr let*-bindings) (cdr mv-bindings))))
  706.            `(progn ,@(setters) nil))))
  707.       (thunk (let*-bindings) (mv-bindings)))))
  708.  
  709.  
  710. (defmacro shiftf (&rest args &environment env)
  711.   "One or more SETF-style place expressions, followed by a single
  712.    value expression.  Evaluates all of the expressions in turn, then
  713.    assigns the value of each expression to the place on its left,
  714.    returning the value of the leftmost."
  715.   (if (< (length args) 2)
  716.       (error "Too few argument forms to a SHIFTF."))
  717.   (collect ((let*-bindings) (forms))
  718.     (do ((first t nil)
  719.      (a args (cdr a))
  720.      (prev-store-vars)
  721.      (prev-setter))
  722.     ((endp (cdr a))
  723.      (forms `(multiple-value-bind ,prev-store-vars ,(car a)
  724.            ,prev-setter)))
  725.       (multiple-value-bind
  726.       (temps exprs store-vars setter getter)
  727.       (get-setf-method-multiple-value (car a) env)
  728.     (loop
  729.       for temp in temps
  730.       for expr in exprs
  731.       do (let*-bindings `(,temp ,expr)))
  732.     (forms (if first
  733.            getter
  734.            `(multiple-value-bind ,prev-store-vars ,getter
  735.               ,prev-setter)))
  736.     (setf prev-store-vars store-vars)
  737.     (setf prev-setter setter)))
  738.     `(let* ,(let*-bindings)
  739.        (multiple-value-prog1
  740.        ,@(forms)))))
  741.  
  742. (defmacro rotatef (&rest args &environment env)
  743.   "Takes any number of SETF-style place expressions.  Evaluates all of the
  744.    expressions in turn, then assigns to each place the value of the form to
  745.    its right.  The rightmost form gets the value of the leftmost.
  746.    Returns NIL."
  747.   (when args
  748.     (collect ((let*-bindings) (mv-bindings) (setters) (getters))
  749.       (dolist (arg args)
  750.     (multiple-value-bind
  751.         (temps subforms store-vars setter getter)
  752.         (get-setf-method-multiple-value arg env)
  753.       (loop
  754.         for temp in temps
  755.         for subform in subforms
  756.         do (let*-bindings `(,temp ,subform)))
  757.       (mv-bindings store-vars)
  758.       (setters setter)
  759.       (getters getter)))
  760.       (setters nil)
  761.       (getters (car (getters)))
  762.       (labels ((thunk (mv-bindings getters)
  763.          (if mv-bindings
  764.              `((multiple-value-bind
  765.                ,(car mv-bindings)
  766.                ,(car getters)
  767.              ,@(thunk (cdr mv-bindings) (cdr getters))))
  768.              (setters))))
  769.     `(let* ,(let*-bindings)
  770.        ,@(thunk (mv-bindings) (cdr (getters))))))))
  771.  
  772.  
  773. (defmacro define-modify-macro (name lambda-list function &optional doc-string)
  774.   "Creates a new read-modify-write macro like PUSH or INCF."
  775.   (let ((other-args nil)
  776.     (rest-arg nil)
  777.     (env (gensym))
  778.     (reference (gensym)))
  779.          
  780.     ;; Parse out the variable names and rest arg from the lambda list.
  781.     (do ((ll lambda-list (cdr ll))
  782.      (arg nil))
  783.     ((null ll))
  784.       (setq arg (car ll))
  785.       (cond ((eq arg '&optional))
  786.         ((eq arg '&rest)
  787.          (if (symbolp (cadr ll))
  788.          (setq rest-arg (cadr ll))
  789.          (error "Non-symbol &rest arg in definition of ~S." name))
  790.          (if (null (cddr ll))
  791.          (return nil)
  792.          (error "Illegal stuff after &rest arg in Define-Modify-Macro.")))
  793.         ((memq arg '(&key &allow-other-keys &aux))
  794.          (error "~S not allowed in Define-Modify-Macro lambda list." arg))
  795.         ((symbolp arg)
  796.          (push arg other-args))
  797.         ((and (listp arg) (symbolp (car arg)))
  798.          (push (car arg) other-args))
  799.         (t (error "Illegal stuff in lambda list of Define-Modify-Macro."))))
  800.     (setq other-args (nreverse other-args))
  801.     `(defmacro ,name (,reference ,@lambda-list &environment ,env)
  802.        ,doc-string
  803.        (multiple-value-bind (dummies vals newval setter getter)
  804.      (get-setf-method ,reference ,env)
  805.      (do ((d dummies (cdr d))
  806.           (v vals (cdr v))
  807.           (let-list nil (cons (list (car d) (car v)) let-list)))
  808.          ((null d)
  809.           (push 
  810.            (list (car newval)
  811.              ,(if rest-arg
  812.               `(list* ',function getter ,@other-args ,rest-arg)
  813.               `(list ',function getter ,@other-args)))
  814.            let-list)
  815.           `(let* ,(nreverse let-list)
  816.          ,setter)))))))
  817.  
  818.  
  819.  
  820. (defmacro push (obj place &environment env)
  821.   "Takes an object and a location holding a list.  Conses the object onto
  822.   the list, returning the modified list."
  823.   (if (symbolp place)
  824.       `(setq ,place (cons ,obj ,place))
  825.       (multiple-value-bind (dummies vals newval setter getter)
  826.                (get-setf-method place env)
  827.     (do* ((d dummies (cdr d))
  828.           (v vals (cdr v))
  829.           (let-list nil))
  830.          ((null d)
  831.           (push (list (car newval) `(cons ,obj ,getter))
  832.             let-list)
  833.           `(let* ,(nreverse let-list)
  834.          ,setter))
  835.       (push (list (car d) (car v)) let-list)))))
  836.  
  837.  
  838. (defmacro pushnew (obj place &rest keys &environment env)
  839.   "Takes an object and a location holding a list.  If the object is already
  840.   in the list, does nothing.  Else, conses the object onto the list.  Returns
  841.   NIL.  If there is a :TEST keyword, this is used for the comparison."
  842.   (if (symbolp place)
  843.       `(setq ,place (adjoin ,obj ,place ,@keys))
  844.       (multiple-value-bind (dummies vals newval setter getter)
  845.                (get-setf-method place env)
  846.     (do* ((d dummies (cdr d))
  847.           (v vals (cdr v))
  848.           (let-list nil))
  849.          ((null d)
  850.           (push (list (car newval) `(adjoin ,obj ,getter ,@keys))
  851.             let-list)
  852.           `(let* ,(nreverse let-list)
  853.          ,setter))
  854.       (push (list (car d) (car v)) let-list)))))
  855.  
  856.  
  857. (defmacro pop (place &environment env)
  858.   "The argument is a location holding a list.  Pops one item off the front
  859.   of the list and returns it."
  860.   (if (symbolp place)
  861.       `(prog1 (car ,place) (setq ,place (cdr ,place)))
  862.       (multiple-value-bind (dummies vals newval setter getter)
  863.                (get-setf-method place env)
  864.     (do* ((d dummies (cdr d))
  865.           (v vals (cdr v))
  866.           (let-list nil))
  867.          ((null d)
  868.           (push (list (car newval) getter) let-list)
  869.           `(let* ,(nreverse let-list)
  870.          (prog1 (car ,(car newval))
  871.             (setq ,(car newval) (cdr ,(car newval)))
  872.             ,setter)))
  873.       (push (list (car d) (car v)) let-list)))))
  874.  
  875.  
  876. (define-modify-macro incf (&optional (delta 1)) +
  877.   "The first argument is some location holding a number.  This number is
  878.   incremented by the second argument, DELTA, which defaults to 1.")
  879.  
  880.  
  881. (define-modify-macro decf (&optional (delta 1)) -
  882.   "The first argument is some location holding a number.  This number is
  883.   decremented by the second argument, DELTA, which defaults to 1.")
  884.  
  885.  
  886. (defmacro remf (place indicator &environment env)
  887.   "Place may be any place expression acceptable to SETF, and is expected
  888.   to hold a property list or ().  This list is destructively altered to
  889.   remove the property specified by the indicator.  Returns T if such a
  890.   property was present, NIL if not."
  891.   (multiple-value-bind (dummies vals newval setter getter)
  892.                (get-setf-method place env)
  893.     (do* ((d dummies (cdr d))
  894.       (v vals (cdr v))
  895.       (let-list nil)
  896.       (ind-temp (gensym))
  897.       (local1 (gensym))
  898.       (local2 (gensym)))
  899.      ((null d)
  900.       (push (list (car newval) getter) let-list)
  901.       (push (list ind-temp indicator) let-list)
  902.       `(let* ,(nreverse let-list)
  903.          (do ((,local1 ,(car newval) (cddr ,local1))
  904.           (,local2 nil ,local1))
  905.          ((atom ,local1) nil)
  906.            (cond ((atom (cdr ,local1))
  907.               (error "Odd-length property list in REMF."))
  908.              ((eq (car ,local1) ,ind-temp)
  909.               (cond (,local2
  910.                  (rplacd (cdr ,local2) (cddr ,local1))
  911.                  (return t))
  912.                 (t (setq ,(car newval) (cddr ,(car newval)))
  913.                    ,setter
  914.                    (return t))))))))
  915.       (push (list (car d) (car v)) let-list))))
  916.  
  917.  
  918. ;;; The built-in DEFSETFs.
  919.  
  920. (defsetf car %rplaca)
  921. (defsetf cdr %rplacd)
  922. (defsetf caar (x) (v) `(%rplaca (car ,x) ,v))
  923. (defsetf cadr (x) (v) `(%rplaca (cdr ,x) ,v))
  924. (defsetf cdar (x) (v) `(%rplacd (car ,x) ,v))
  925. (defsetf cddr (x) (v) `(%rplacd (cdr ,x) ,v))
  926. (defsetf caaar (x) (v) `(%rplaca (caar ,x) ,v))
  927. (defsetf cadar (x) (v) `(%rplaca (cdar ,x) ,v))
  928. (defsetf cdaar (x) (v) `(%rplacd (caar ,x) ,v))
  929. (defsetf cddar (x) (v) `(%rplacd (cdar ,x) ,v))
  930. (defsetf caadr (x) (v) `(%rplaca (cadr ,x) ,v))
  931. (defsetf caddr (x) (v) `(%rplaca (cddr ,x) ,v))
  932. (defsetf cdadr (x) (v) `(%rplacd (cadr ,x) ,v))
  933. (defsetf cdddr (x) (v) `(%rplacd (cddr ,x) ,v))
  934. (defsetf caaaar (x) (v) `(%rplaca (caaar ,x) ,v))
  935. (defsetf cadaar (x) (v) `(%rplaca (cdaar ,x) ,v))
  936. (defsetf cdaaar (x) (v) `(%rplacd (caaar ,x) ,v))
  937. (defsetf cddaar (x) (v) `(%rplacd (cdaar ,x) ,v))
  938. (defsetf caadar (x) (v) `(%rplaca (cadar ,x) ,v))
  939. (defsetf caddar (x) (v) `(%rplaca (cddar ,x) ,v))
  940. (defsetf cdadar (x) (v) `(%rplacd (cadar ,x) ,v))
  941. (defsetf cdddar (x) (v) `(%rplacd (cddar ,x) ,v))
  942. (defsetf caaadr (x) (v) `(%rplaca (caadr ,x) ,v))
  943. (defsetf cadadr (x) (v) `(%rplaca (cdadr ,x) ,v))
  944. (defsetf cdaadr (x) (v) `(%rplacd (caadr ,x) ,v))
  945. (defsetf cddadr (x) (v) `(%rplacd (cdadr ,x) ,v))
  946. (defsetf caaddr (x) (v) `(%rplaca (caddr ,x) ,v))
  947. (defsetf cadddr (x) (v) `(%rplaca (cdddr ,x) ,v))
  948. (defsetf cdaddr (x) (v) `(%rplacd (caddr ,x) ,v))
  949. (defsetf cddddr (x) (v) `(%rplacd (cdddr ,x) ,v))
  950.  
  951. (defsetf first %rplaca)
  952. (defsetf second (x) (v) `(%rplaca (cdr ,x) ,v))
  953. (defsetf third (x) (v) `(%rplaca (cddr ,x) ,v))
  954. (defsetf fourth (x) (v) `(%rplaca (cdddr ,x) ,v))
  955. (defsetf fifth (x) (v) `(%rplaca (cddddr ,x) ,v))
  956. (defsetf sixth (x) (v) `(%rplaca (cdr (cddddr ,x)) ,v))
  957. (defsetf seventh (x) (v) `(%rplaca (cddr (cddddr ,x)) ,v))
  958. (defsetf eighth (x) (v) `(%rplaca (cdddr (cddddr ,x)) ,v))
  959. (defsetf ninth (x) (v) `(%rplaca (cddddr (cddddr ,x)) ,v))
  960. (defsetf tenth (x) (v) `(%rplaca (cdr (cddddr (cddddr ,x))) ,v))
  961. (defsetf rest %rplacd)
  962.  
  963. (defsetf elt %setelt)
  964. (defsetf aref %aset)
  965. (defsetf row-major-aref %set-row-major-aref)
  966. (defsetf svref %svset)
  967. (defsetf char %charset)
  968. (defsetf bit %bitset)
  969. (defsetf schar %scharset)
  970. (defsetf sbit %sbitset)
  971. (defsetf %array-dimension %set-array-dimension)
  972. (defsetf %raw-bits %set-raw-bits)
  973. (defsetf symbol-value set)
  974. (defsetf symbol-function fset)
  975. (defsetf symbol-plist %set-symbol-plist)
  976. (defsetf documentation %set-documentation)
  977. (defsetf nth %setnth)
  978. (defsetf fill-pointer %set-fill-pointer)
  979. (defsetf search-list %set-search-list)
  980.  
  981. (defsetf sap-ref-8 %set-sap-ref-8)
  982. (defsetf signed-sap-ref-8 %set-signed-sap-ref-8)
  983. (defsetf sap-ref-16 %set-sap-ref-16)
  984. (defsetf signed-sap-ref-16 %set-signed-sap-ref-16)
  985. (defsetf sap-ref-32 %set-sap-ref-32)
  986. (defsetf signed-sap-ref-32 %set-signed-sap-ref-32)
  987. (defsetf sap-ref-sap %set-sap-ref-sap)
  988. (defsetf sap-ref-single %set-sap-ref-single)
  989. (defsetf sap-ref-double %set-sap-ref-double)
  990.  
  991. (define-setf-method getf (place prop &optional default &environment env)
  992.   (multiple-value-bind (temps values stores set get)
  993.                (get-setf-method place env)
  994.     (let ((newval (gensym))
  995.       (ptemp (gensym))
  996.       (def-temp (if default (gensym))))
  997.       (values `(,@temps ,ptemp ,@(if default `(,def-temp)))
  998.           `(,@values ,prop ,@(if default `(,default)))
  999.           `(,newval)
  1000.           `(let ((,(car stores) (%putf ,get ,ptemp ,newval)))
  1001.          ,set
  1002.          ,newval)
  1003.           `(getf ,get ,ptemp ,@(if default `(,def-temp)))))))
  1004.  
  1005. (define-setf-method get (symbol prop &optional default)
  1006.   (let ((symbol-temp (gensym))
  1007.     (prop-temp (gensym))
  1008.     (def-temp (gensym))
  1009.     (newval (gensym)))
  1010.     (values `(,symbol-temp ,prop-temp ,@(if default `(,def-temp)))
  1011.         `(,symbol ,prop ,@(if default `(,default)))
  1012.         (list newval)
  1013.         `(%put ,symbol-temp ,prop-temp ,newval)
  1014.         `(get ,symbol-temp ,prop-temp ,@(if default `(,def-temp))))))
  1015.  
  1016. (define-setf-method gethash (key hashtable &optional default)
  1017.   (let ((key-temp (gensym))
  1018.     (hashtable-temp (gensym))
  1019.     (default-temp (gensym))
  1020.     (new-value-temp (gensym)))
  1021.     (values
  1022.      `(,key-temp ,hashtable-temp ,@(if default `(,default-temp)))
  1023.      `(,key ,hashtable ,@(if default `(,default)))
  1024.      `(,new-value-temp)
  1025.      `(%puthash ,key-temp ,hashtable-temp ,new-value-temp)
  1026.      `(gethash ,key-temp ,hashtable-temp ,@(if default `(,default-temp))))))
  1027.  
  1028. (defsetf subseq (sequence start &optional (end nil)) (v)
  1029.   `(progn (replace ,sequence ,v :start1 ,start :end1 ,end)
  1030.       ,v))
  1031.  
  1032.  
  1033. ;;; Evil hack invented by the gnomes of Vassar Street.  The function arg must
  1034. ;;; be constant.  Get a setf method for this function, pretending that the
  1035. ;;; final (list) arg to apply is just a normal arg.  If the setting and access
  1036. ;;; forms produced in this way reference this arg at the end, then just splice
  1037. ;;; the APPLY back onto the front and the right thing happens.
  1038. ;;;
  1039. ;;; We special-case uses functions in the Lisp package so that APPLY AREF works
  1040. ;;; even though %ASET takes the new-value last.  (there is (SETF AREF) as well
  1041. ;;; as a setf method, etc.)
  1042. ;;;
  1043. (define-setf-method apply (function &rest args &environment env)
  1044.   (unless (and (listp function)
  1045.            (= (list-length function) 2)
  1046.            (eq (first function) 'function)
  1047.            (symbolp (second function)))
  1048.     (error "Setf of Apply is only defined for function args like #'symbol."))
  1049.   (let ((function (second function)))
  1050.     (multiple-value-bind
  1051.     (dummies vals newval setter getter)
  1052.     (if (eq (symbol-package function) (symbol-package 'aref))
  1053.         (get-setf-method-inverse (cons function args) `((setf ,function)) t)
  1054.         (get-setf-method (cons function args) env))
  1055.       (unless (and (eq (car (last args)) (car (last vals)))
  1056.            (eq (car (last getter)) (car (last dummies)))
  1057.            (eq (car (last setter)) (car (last dummies))))
  1058.     (error "Apply of ~S not understood as a location for Setf." function))
  1059.       (values dummies vals newval
  1060.           `(apply (function ,(car setter)) ,@(cdr setter))
  1061.           `(apply (function ,(car getter)) ,@(cdr getter))))))
  1062.  
  1063.  
  1064. ;;; Special-case a BYTE bytespec so that the compiler can recognize it.
  1065. ;;;
  1066. (define-setf-method ldb (bytespec place &environment env)
  1067.   "The first argument is a byte specifier.  The second is any place form
  1068.   acceptable to SETF.  Replaces the specified byte of the number in this
  1069.   place with bits from the low-order end of the new value."
  1070.   (multiple-value-bind (dummies vals newval setter getter)
  1071.                (get-setf-method place env)
  1072.     (if (and (consp bytespec) (eq (car bytespec) 'byte))
  1073.     (let ((n-size (gensym))
  1074.           (n-pos (gensym))
  1075.           (n-new (gensym)))
  1076.       (values (list* n-size n-pos dummies)
  1077.           (list* (second bytespec) (third bytespec) vals)
  1078.           (list n-new)
  1079.           `(let ((,(car newval) (dpb ,n-new (byte ,n-size ,n-pos)
  1080.                          ,getter)))
  1081.              ,setter
  1082.              ,n-new)
  1083.           `(ldb (byte ,n-size ,n-pos) ,getter)))
  1084.     (let ((btemp (gensym))
  1085.           (gnuval (gensym)))
  1086.       (values (cons btemp dummies)
  1087.           (cons bytespec vals)
  1088.           (list gnuval)
  1089.           `(let ((,(car newval) (dpb ,gnuval ,btemp ,getter)))
  1090.              ,setter
  1091.              ,gnuval)
  1092.           `(ldb ,btemp ,getter))))))
  1093.  
  1094.  
  1095. (define-setf-method mask-field (bytespec place &environment env)
  1096.   "The first argument is a byte specifier.  The second is any place form
  1097.   acceptable to SETF.  Replaces the specified byte of the number in this place
  1098.   with bits from the corresponding position in the new value."
  1099.   (multiple-value-bind (dummies vals newval setter getter)
  1100.                (get-setf-method place env)
  1101.     (let ((btemp (gensym))
  1102.       (gnuval (gensym)))
  1103.       (values (cons btemp dummies)
  1104.           (cons bytespec vals)
  1105.           (list gnuval)
  1106.           `(let ((,(car newval) (deposit-field ,gnuval ,btemp ,getter)))
  1107.          ,setter
  1108.          ,gnuval)
  1109.           `(mask-field ,btemp ,getter)))))
  1110.  
  1111.  
  1112. (define-setf-method the (type place &environment env)
  1113.   (multiple-value-bind (dummies vals newval setter getter)
  1114.                (get-setf-method place env)
  1115.       (values dummies
  1116.           vals
  1117.           newval
  1118.           (subst `(the ,type ,(car newval)) (car newval) setter)
  1119.           `(the ,type ,getter))))
  1120.  
  1121.  
  1122. ;;;; CASE, TYPECASE, & Friends.
  1123.  
  1124. (eval-when (compile load eval)
  1125.  
  1126. ;;; CASE-BODY returns code for all the standard "case" macros.  Name is the
  1127. ;;; macro name, and keyform is the thing to case on.  Multi-p indicates whether
  1128. ;;; a branch may fire off a list of keys; otherwise, a key that is a list is
  1129. ;;; interpreted in some way as a single key.  When multi-p, test is applied to
  1130. ;;; the value of keyform and each key for a given branch; otherwise, test is
  1131. ;;; applied to the value of keyform and the entire first element, instead of
  1132. ;;; each part, of the case branch.  When errorp, no t or otherwise branch is
  1133. ;;; permitted, and an ERROR form is generated.  When proceedp, it is an error
  1134. ;;; to omit errorp, and the ERROR form generated is executed within a
  1135. ;;; RESTART-CASE allowing keyform to be set and retested.
  1136. ;;;
  1137. (defun case-body (name keyform cases multi-p test errorp proceedp)
  1138.   (let ((keyform-value (gensym))
  1139.     (clauses ())
  1140.     (keys ()))
  1141.     (dolist (case cases)
  1142.       (cond ((atom case)
  1143.          (error "~S -- Bad clause in ~S." case name))
  1144.         ((memq (car case) '(t otherwise))
  1145.          (if errorp
  1146.          (error "No default clause allowed in ~S: ~S" name case)
  1147.          (push `(t nil ,@(rest case)) clauses)))
  1148.         ((and multi-p (listp (first case)))
  1149.          (setf keys (append (first case) keys))
  1150.          (push `((or ,@(mapcar #'(lambda (key)
  1151.                        `(,test ,keyform-value ',key))
  1152.                    (first case)))
  1153.              nil ,@(rest case))
  1154.            clauses))
  1155.         (t
  1156.          (push (first case) keys)
  1157.          (push `((,test ,keyform-value
  1158.                 ',(first case)) nil ,@(rest case)) clauses))))
  1159.     (case-body-aux name keyform keyform-value clauses keys errorp proceedp
  1160.            `(,(if multi-p 'member 'or) ,@keys))))
  1161.  
  1162. ;;; CASE-BODY-AUX provides the expansion once CASE-BODY has groveled all the
  1163. ;;; cases.  Note: it is not necessary that the resulting code signal
  1164. ;;; case-failure conditions, but that's what KMP's prototype code did.  We call
  1165. ;;; CASE-BODY-ERROR, because of how closures are compiled.  RESTART-CASE has
  1166. ;;; forms with closures that the compiler causes to be generated at the top of
  1167. ;;; any function using the case macros, regardless of whether they are needed.
  1168. ;;;
  1169. (defun case-body-aux (name keyform keyform-value clauses keys
  1170.               errorp proceedp expected-type)
  1171.   (if proceedp
  1172.       (let ((block (gensym))
  1173.         (again (gensym)))
  1174.     `(let ((,keyform-value ,keyform))
  1175.        (block ,block
  1176.          (tagbody
  1177.           ,again
  1178.           (return-from
  1179.            ,block
  1180.            (cond ,@(nreverse clauses)
  1181.              (t
  1182.               (setf ,keyform-value
  1183.                 (setf ,keyform
  1184.                   (case-body-error
  1185.                    ',name ',keyform ,keyform-value
  1186.                    ',expected-type ',keys)))
  1187.               (go ,again))))))))
  1188.       `(let ((,keyform-value ,keyform))
  1189.      (cond
  1190.       ,@(nreverse clauses)
  1191.       ,@(if errorp
  1192.         `((t (error 'conditions::case-failure
  1193.                 :name ',name
  1194.                 :datum ,keyform-value
  1195.                 :expected-type ',expected-type
  1196.                 :possibilities ',keys))))))))
  1197.  
  1198. ); eval-when
  1199.  
  1200. (defun case-body-error (name keyform keyform-value expected-type keys)
  1201.   (restart-case
  1202.       (error 'conditions::case-failure
  1203.          :name name
  1204.          :datum keyform-value
  1205.          :expected-type expected-type
  1206.          :possibilities keys)
  1207.     (store-value (value)
  1208.       :report (lambda (stream)
  1209.         (format stream "Supply a new value for ~S." keyform))
  1210.       :interactive read-evaluated-form
  1211.       value)))
  1212.  
  1213.  
  1214. (defmacro case (keyform &body cases)
  1215.   "CASE Keyform {({(Key*) | Key} Form*)}*
  1216.   Evaluates the Forms in the first clause with a Key EQL to the value of
  1217.   Keyform.  If a singleton key is T then the clause is a default clause."
  1218.   (case-body 'case keyform cases t 'eql nil nil))
  1219.  
  1220. (defmacro ccase (keyform &body cases)
  1221.   "CCASE Keyform {({(Key*) | Key} Form*)}*
  1222.   Evaluates the Forms in the first clause with a Key EQL to the value of
  1223.   Keyform.  If none of the keys matches then a correctable error is
  1224.   signalled."
  1225.   (case-body 'ccase keyform cases t 'eql t t))
  1226.  
  1227. (defmacro ecase (keyform &body cases)
  1228.   "ECASE Keyform {({(Key*) | Key} Form*)}*
  1229.   Evaluates the Forms in the first clause with a Key EQL to the value of
  1230.   Keyform.  If none of the keys matches then an error is signalled."
  1231.   (case-body 'ecase keyform cases t 'eql t nil))
  1232.  
  1233. (defmacro typecase (keyform &body cases)
  1234.   "TYPECASE Keyform {(Type Form*)}*
  1235.   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
  1236.   is true."
  1237.   (case-body 'typecase keyform cases nil 'typep nil nil))
  1238.  
  1239. (defmacro ctypecase (keyform &body cases)
  1240.   "CTYPECASE Keyform {(Type Form*)}*
  1241.   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
  1242.   is true.  If no form is satisfied then a correctable error is signalled."
  1243.   (case-body 'ctypecase keyform cases nil 'typep t t))
  1244.  
  1245. (defmacro etypecase (keyform &body cases)
  1246.   "ETYPECASE Keyform {(Type Form*)}*
  1247.   Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
  1248.   is true.  If no form is satisfied then an error is signalled."
  1249.   (case-body 'etypecase keyform cases nil 'typep t nil))
  1250.  
  1251.  
  1252. ;;;; ASSERT and CHECK-TYPE.
  1253.  
  1254. ;;; ASSERT is written this way, to call ASSERT-ERROR, because of how closures
  1255. ;;; are compiled.  RESTART-CASE has forms with closures that the compiler
  1256. ;;; causes to be generated at the top of any function using ASSERT, regardless
  1257. ;;; of whether they are needed.
  1258. ;;;
  1259. (defmacro assert (test-form &optional places datum &rest arguments)
  1260.   "Signals an error if the value of test-form is nil.  Continuing from this
  1261.    error using the CONTINUE restart will allow the user to alter the value of
  1262.    some locations known to SETF, starting over with test-form.  Returns nil."
  1263.   `(loop
  1264.      (when ,test-form (return nil))
  1265.      (assert-error ',test-form ',places ,datum ,@arguments)
  1266.      ,@(mapcar #'(lambda (place)
  1267.            `(setf ,place (assert-prompt ',place ,place)))
  1268.            places)))
  1269.  
  1270. (defun assert-error (test-form places datum &rest arguments)
  1271.   (restart-case (if datum
  1272.             (apply #'error datum arguments)
  1273.             (simple-assertion-failure test-form))
  1274.     (continue ()
  1275.       :report (lambda (stream) (assert-report places stream))
  1276.       nil)))
  1277.  
  1278. (defun simple-assertion-failure (assertion)
  1279.   (error 'simple-type-error
  1280.      :datum assertion
  1281.      :expected-type nil ;this needs some work in next revision. -kmp
  1282.      :format-string "The assertion ~S failed."
  1283.      :format-arguments (list assertion)))
  1284.  
  1285. (defun assert-report (names stream)
  1286.   (format stream "Retry assertion")
  1287.   (if names
  1288.       (format stream " with new value~P for ~{~S~^, ~}."
  1289.           (length names) names)
  1290.       (format stream ".")))
  1291.  
  1292. (defun assert-prompt (name value)
  1293.   (cond ((y-or-n-p "The old value of ~S is ~S.~
  1294.           ~%Do you want to supply a new value? "
  1295.            name value)
  1296.      (format *query-io* "~&Type a form to be evaluated:~%")
  1297.      (flet ((read-it () (eval (read *query-io*))))
  1298.        (if (symbolp name) ;help user debug lexical variables
  1299.            (progv (list name) (list value) (read-it))
  1300.            (read-it))))
  1301.     (t value)))
  1302.  
  1303.  
  1304. ;;; CHECK-TYPE is written this way, to call CHECK-TYPE-ERROR, because of how
  1305. ;;; closures are compiled.  RESTART-CASE has forms with closures that the
  1306. ;;; compiler causes to be generated at the top of any function using
  1307. ;;; CHECK-TYPE, regardless of whether they are needed.  Because it would be
  1308. ;;; nice if this were cheap to use, and some things can't afford this excessive
  1309. ;;; consing (e.g., READ-CHAR), we bend backwards a little.
  1310. ;;;
  1311.  
  1312. (defmacro check-type (place type &optional type-string)
  1313.   "Signals an error of type type-error if the contents of place are not of the
  1314.    specified type.  If an error is signaled, this can only return if
  1315.    STORE-VALUE is invoked.  It will store into place and start over."
  1316.   (let ((place-value (gensym)))
  1317.     `(loop
  1318.        (let ((,place-value ,place))
  1319.      (when (typep ,place-value ',type) (return nil))
  1320.      (setf ,place
  1321.            (check-type-error ',place ,place-value ',type ,type-string))))))
  1322.  
  1323. (defun check-type-error (place place-value type type-string)
  1324.   (restart-case (if type-string
  1325.             (error 'simple-type-error
  1326.                :datum place :expected-type type
  1327.                :format-string
  1328.                "The value of ~S is ~S, which is not ~A."
  1329.                :format-arguments
  1330.                (list place place-value type-string))
  1331.             (error 'simple-type-error
  1332.                :datum place :expected-type type
  1333.                :format-string
  1334.                "The value of ~S is ~S, which is not of type ~S."
  1335.                :format-arguments
  1336.                (list place place-value type)))
  1337.     (store-value (value)
  1338.       :report (lambda (stream)
  1339.         (format stream "Supply a new value of ~S."
  1340.             place))
  1341.       :interactive read-evaluated-form
  1342.       value)))
  1343.  
  1344. ;;; READ-EVALUATED-FORM is used as the interactive method for restart cases
  1345. ;;; setup by the Common Lisp "casing" (e.g., CCASE and CTYPECASE) macros
  1346. ;;; and by CHECK-TYPE.
  1347. ;;;
  1348. (defun read-evaluated-form ()
  1349.   (format *query-io* "~&Type a form to be evaluated:~%")
  1350.   (list (eval (read *query-io*))))
  1351.  
  1352.  
  1353. ;;;; With-XXX
  1354.  
  1355. (defmacro with-open-file ((var &rest open-args) &body (forms decls))
  1356.   "Bindspec is of the form (Stream File-Name . Options).  The file whose
  1357.    name is File-Name is opened using the Options and bound to the variable
  1358.    Stream.  If the call to open is unsuccessful, the forms are not
  1359.    evaluated.  The Forms are executed, and when they terminate, normally or
  1360.    otherwise, the file is closed."
  1361.   (let ((abortp (gensym)))
  1362.     `(let ((,var (open ,@open-args))
  1363.        (,abortp t))
  1364.        ,@decls
  1365.        (when ,var
  1366.      (unwind-protect
  1367.          (multiple-value-prog1
  1368.          (progn ,@forms)
  1369.            (setq ,abortp nil))
  1370.        (close ,var :abort ,abortp))))))
  1371.  
  1372.  
  1373.  
  1374. (defmacro with-open-stream ((var stream) &body (forms decls))
  1375.   "The form stream should evaluate to a stream.  VAR is bound
  1376.    to the stream and the forms are evaluated as an implicit
  1377.    progn.  The stream is closed upon exit."
  1378.   (let ((abortp (gensym)))
  1379.     `(let ((,var ,stream)
  1380.        (,abortp t))
  1381.        ,@decls
  1382.        (unwind-protect
  1383.      (multiple-value-prog1
  1384.       (progn ,@forms)
  1385.       (setq ,abortp nil))
  1386.      (when ,var
  1387.        (close ,var :abort ,abortp))))))
  1388.  
  1389.  
  1390. (defmacro with-input-from-string ((var string &key index start end) &body (forms decls))
  1391.   "Binds the Var to an input stream that returns characters from String and
  1392.   executes the body.  See manual for details."
  1393.   `(let ((,var
  1394.       ,(if end
  1395.            `(make-string-input-stream ,string ,(or start 0) ,end)
  1396.            `(make-string-input-stream ,string ,(or start 0)))))
  1397.      ,@decls
  1398.      (unwind-protect
  1399.        (progn ,@forms)
  1400.        (close ,var)
  1401.        ,@(if index `((setf ,index (string-input-stream-current ,var)))))))
  1402.  
  1403.  
  1404. (defmacro with-output-to-string ((var &optional string) &body (forms decls))
  1405.   "If *string* is specified, it must be a string with a fill pointer; 
  1406.    the output is incrementally appended to the string (as if by use of
  1407.    VECTOR-PUSH-EXTEND)."
  1408.   (if string
  1409.       `(let ((,var (make-fill-pointer-output-stream ,string)))
  1410.      ,@decls
  1411.      (unwind-protect
  1412.        (progn ,@forms)
  1413.        (close ,var)))
  1414.       `(let ((,var (make-string-output-stream)))
  1415.      ,@decls
  1416.      (unwind-protect
  1417.        (progn ,@forms)
  1418.        (close ,var))
  1419.      (get-output-stream-string ,var))))
  1420.  
  1421.  
  1422. ;;;; Iteration macros:
  1423.  
  1424. (defmacro dotimes ((var count &optional (result nil)) &body body)
  1425.   (cond ((numberp count)
  1426.          `(do ((,var 0 (1+ ,var)))
  1427.               ((>= ,var ,count) ,result)
  1428.         (declare (type unsigned-byte ,var))
  1429.             ,@body))
  1430.         (t (let ((v1 (gensym)))
  1431.              `(do ((,var 0 (1+ ,var)) (,v1 ,count))
  1432.                   ((>= ,var ,v1) ,result)
  1433.         (declare (type unsigned-byte ,var))
  1434.                 ,@body)))))
  1435.  
  1436.  
  1437. ;;; We repeatedly bind the var instead of setting it so that we never give the
  1438. ;;; var a random value such as NIL (which might conflict with a declaration).
  1439. ;;; If there is a result form, we introduce a gratitous binding of the variable
  1440. ;;; to NIL w/o the declarations, then evaluate the result form in that
  1441. ;;; environment.  We spuriously reference the gratuitous variable, since we
  1442. ;;; don't want to use IGNORABLE on what might be a special var.
  1443. ;;;
  1444. (defmacro dolist ((var list &optional (result nil)) &body body)
  1445.   (let ((n-list (gensym)))
  1446.     `(do ((,n-list ,list (cdr ,n-list)))
  1447.      ((endp ,n-list)
  1448.       ,@(if result
  1449.         `((let ((,var nil))
  1450.             ,var
  1451.             ,result))
  1452.         '(nil)))
  1453.        (let ((,var (car ,n-list)))
  1454.      ,@body))))
  1455.  
  1456.  
  1457. (defmacro do (varlist endlist &body (body decls))
  1458.   "DO ({(Var [Init] [Step])}*) (Test Exit-Form*) Declaration* Form*
  1459.   Iteration construct.  Each Var is initialized in parallel to the value of the
  1460.   specified Init form.  On subsequent iterations, the Vars are assigned the
  1461.   value of the Step form (if any) in paralell.  The Test is evaluated before
  1462.   each evaluation of the body Forms.  When the Test is true, the the Exit-Forms
  1463.   are evaluated as a PROGN, with the result being the value of the DO.  A block
  1464.   named NIL is established around the entire expansion, allowing RETURN to be
  1465.   used as an laternate exit mechanism."
  1466.  
  1467.   (do-do-body varlist endlist body decls 'let 'psetq 'do nil))
  1468.  
  1469.  
  1470. (defmacro do* (varlist endlist &body (body decls))
  1471.   "DO* ({(Var [Init] [Step])}*) (Test Exit-Form*) Declaration* Form*
  1472.   Iteration construct.  Each Var is initialized sequentially (like LET*) to the
  1473.   value of the specified Init form.  On subsequent iterations, the Vars are
  1474.   sequentially assigned the value of the Step form (if any).  The Test is
  1475.   evaluated before each evaluation of the body Forms.  When the Test is true,
  1476.   the the Exit-Forms are evaluated as a PROGN, with the result being the value
  1477.   of the DO.  A block named NIL is established around the entire expansion,
  1478.   allowing RETURN to be used as an laternate exit mechanism."
  1479.   (do-do-body varlist endlist body decls 'let* 'setq 'do* nil))
  1480.  
  1481.  
  1482. ;;;; Miscellaneous macros:
  1483.  
  1484. (defmacro locally (&rest forms)
  1485.   "A form providing a container for locally-scoped variables."
  1486.   `(let () ,@forms))
  1487.  
  1488. (defmacro psetq (&rest pairs)
  1489.   (do ((lets nil)
  1490.        (setqs nil)
  1491.        (pairs pairs (cddr pairs)))
  1492.       ((atom (cdr pairs))
  1493.        `(let ,(nreverse lets) (setq ,@(nreverse setqs))))
  1494.     (let ((gen (gensym)))
  1495.       (push `(,gen ,(cadr pairs)) lets)
  1496.       (push (car pairs) setqs)
  1497.       (push gen setqs))))
  1498.  
  1499.  
  1500. ;;;; With-Compilation-Unit:
  1501.  
  1502. ;;; True if we are within a With-Compilation-Unit form, which normally causes
  1503. ;;; nested uses to be NOOPS.
  1504. ;;;
  1505. (defvar *in-compilation-unit* nil)
  1506.  
  1507. ;;; Count of the number of compilation units dynamically enclosed by the
  1508. ;;; current active WITH-COMPILATION-UNIT that were unwound out of.
  1509. ;;;
  1510. (defvar *aborted-compilation-units*)
  1511.  
  1512. (declaim (special c::*context-declarations*))
  1513.  
  1514.  
  1515. ;;; EVALUATE-DECLARATION-CONTEXT  --  Internal
  1516. ;;;
  1517. ;;;    Recursively descend the context form, returning true if this subpart
  1518. ;;; matches the specified context.
  1519. ;;;
  1520. (defun evaluate-declaration-context (context name parent)
  1521.   (let* ((base (if (and (consp name) (consp (cdr name)))
  1522.            (cadr name)
  1523.            name))
  1524.      (package (and (symbolp base) (symbol-package base))))
  1525.     (if (atom context)
  1526.     (multiple-value-bind (ignore how)
  1527.                  (if package
  1528.                  (find-symbol (symbol-name base) package)
  1529.                  (values nil nil))
  1530.       (declare (ignore ignore))
  1531.       (case context
  1532.         (:internal (eq how :internal))
  1533.         (:external (eq how :external))
  1534.         (:uninterned (and (symbolp base) (not package)))
  1535.         (:anonymous (not name))
  1536.         (:macro (eq parent 'defmacro))
  1537.         (:function (member parent '(defun labels flet function)))
  1538.         (:global (member parent '(defun defmacro function)))
  1539.         (:local (member parent '(labels flet)))
  1540.         (t
  1541.          (error "Unknown declaration context: ~S." context))))
  1542.     (case (first context)
  1543.       (:or
  1544.        (loop for x in (rest context)
  1545.          thereis (evaluate-declaration-context x name parent)))
  1546.       (:and
  1547.        (loop for x in (rest context)
  1548.          always (evaluate-declaration-context x name parent)))
  1549.       (:not
  1550.        (evaluate-declaration-context (second context) name parent))
  1551.       (:member
  1552.        (member name (rest context) :test #'equal))
  1553.       (:match
  1554.        (let ((name (concatenate 'string "$" (string base) "$")))
  1555.          (loop for x in (rest context)
  1556.            thereis (search (string x) name))))
  1557.       (:package
  1558.        (and package
  1559.         (loop for x in (rest context)
  1560.           thereis (eq (find-package (string x)) package))))
  1561.       (t
  1562.        (error "Unknown declaration context: ~S." context))))))
  1563.  
  1564.   
  1565. ;;; PROCESS-CONTEXT-DECLARATIONS  --  Internal
  1566. ;;;
  1567. ;;;    Given a list of context declaration specs, return a new value for
  1568. ;;; C::*CONTEXT-DECLARATIONS*.
  1569. ;;;
  1570. (defun process-context-declarations (decls)
  1571.   (append
  1572.    (mapcar
  1573.     #'(lambda (decl)
  1574.     (unless (>= (length decl) 2)
  1575.       (error "Context declaration spec should have context and at ~
  1576.       least one DECLARE form:~%  ~S" decl))
  1577.     #'(lambda (name parent)
  1578.         (when (evaluate-declaration-context (first decl) name parent)
  1579.           (rest decl))))
  1580.     decls)
  1581.    c::*context-declarations*))
  1582.  
  1583.  
  1584. ;;; With-Compilation-Unit  --  Public
  1585. ;;;
  1586. (defmacro with-compilation-unit (options &body body)
  1587.   "WITH-COMPILATION-UNIT ({Key Value}*) Form*
  1588.   This form affects compilations that take place within its dynamic extent.  It
  1589.   is intended to be wrapped around the compilation of all files in the same
  1590.   system.  These keywords are defined:
  1591.     :OVERRIDE Boolean-Form
  1592.         One of the effects of this form is to delay undefined warnings 
  1593.         until the end of the form, instead of giving them at the end of each
  1594.         compilation.  If OVERRIDE is NIL (the default), then the outermost
  1595.         WITH-COMPILATION-UNIT form grabs the undefined warnings.  Specifying
  1596.         OVERRIDE true causes that form to grab any enclosed warnings, even if
  1597.         it is enclosed by another WITH-COMPILATION-UNIT.
  1598.     :OPTIMIZE Decl-Form
  1599.         Decl-Form should evaluate to an OPTIMIZE declaration specifier.  This
  1600.         declaration changes the `global' policy for compilations within the
  1601.         body.
  1602.     :OPTIMIZE-INTERFACE Decl-Form
  1603.         Like OPTIMIZE, except that it specifies the value of the CMU extension
  1604.         OPTIMIZE-INTERFACE policy (which controls argument type and syntax
  1605.         checking.)
  1606.     :CONTEXT-DECLARATIONS List-of-Context-Decls-Form
  1607.         This is a CMU extension which allows compilation to be controlled
  1608.         by pattern matching on the context in which a definition appears.  The
  1609.         argument should evaluate to a list of lists of the form:
  1610.             (Context-Spec Declare-Form+)
  1611.         In the indicated context, the specified declare forms are inserted at
  1612.         the head of each definition.  The declare forms for all contexts that
  1613.     match are appended together, with earlier declarations getting
  1614.     predecence over later ones.  A simple example:
  1615.             :context-declarations
  1616.             '((:external (declare (optimize (safety 2)))))
  1617.         This will cause all functions that are named by external symbols to be
  1618.         compiled with SAFETY 2.  The full syntax of context specs is:
  1619.     :INTERNAL, :EXTERNAL
  1620.         True if the symbols is internal (external) in its home package.
  1621.     :UNINTERNED
  1622.         True if the symbol has no home package.
  1623.     :ANONYMOUS
  1624.         True if the function doesn't have any interesting name (not
  1625.         DEFMACRO, DEFUN, LABELS or FLET).
  1626.     :MACRO, :FUNCTION
  1627.         :MACRO is a global (DEFMACRO) macro.  :FUNCTION is anything else.
  1628.     :LOCAL, :GLOBAL
  1629.         :LOCAL is a LABELS or FLET.  :GLOBAL is anything else.
  1630.     (:OR Context-Spec*)
  1631.         True in any specified context.
  1632.     (:AND Context-Spec*)
  1633.         True only when all specs are true.
  1634.     (:NOT Context-Spec)
  1635.         True when the spec is false.
  1636.         (:MEMBER Name*)
  1637.         True when the name is one of these names (EQUAL test.)
  1638.     (:MATCH Pattern*)
  1639.         True when any of the patterns is a substring of the name.  The name
  1640.         is wrapped with $'s, so $FOO matches names beginning with FOO,
  1641.         etc."
  1642.   (let ((override nil)
  1643.     (optimize nil)
  1644.     (optimize-interface nil)
  1645.     (context-declarations nil)
  1646.     (n-fun (gensym))
  1647.     (n-abort-p (gensym)))
  1648.     (when (oddp (length options))
  1649.       (error "Odd number of key/value pairs: ~S." options))
  1650.     (do ((opt options (cddr opt)))
  1651.     ((null opt))
  1652.       (case (first opt)
  1653.     (:override
  1654.      (setq override (second opt)))
  1655.     (:optimize
  1656.      (setq optimize (second opt)))
  1657.     (:optimize-interface
  1658.      (setq optimize-interface (second opt)))
  1659.     (:context-declarations
  1660.      (setq context-declarations (second opt)))
  1661.     (t
  1662.      (warn "Ignoring unknown option: ~S." (first opt)))))
  1663.  
  1664.     `(flet ((,n-fun ()
  1665.           (let (,@(when optimize
  1666.             `((c::*default-cookie*
  1667.                (c::process-optimize-declaration
  1668.                 ,optimize c::*default-cookie*))))
  1669.             ,@(when optimize-interface
  1670.             `((c::*default-interface-cookie*
  1671.                (c::process-optimize-declaration
  1672.                 ,optimize-interface
  1673.                 c::*default-interface-cookie*))))
  1674.             ,@(when context-declarations
  1675.             `((c::*context-declarations*
  1676.                (process-context-declarations
  1677.                 ,context-declarations)))))
  1678.         ,@body)))
  1679.        (if (or ,override (not *in-compilation-unit*))
  1680.        (let ((c::*undefined-warnings* nil)
  1681.          (c::*compiler-error-count* 0)
  1682.          (c::*compiler-warning-count* 0)
  1683.          (c::*compiler-note-count* 0)
  1684.          (*in-compilation-unit* t)
  1685.          (*aborted-compilation-units* 0)
  1686.          (,n-abort-p t))
  1687.          (handler-bind ((c::parse-unknown-type
  1688.                  #'(lambda (c)
  1689.                  (c::note-undefined-reference
  1690.                   (c::parse-unknown-type-specifier c)
  1691.                   :type))))
  1692.            (unwind-protect
  1693.            (multiple-value-prog1
  1694.                (,n-fun)
  1695.              (setq ,n-abort-p nil))
  1696.          (c::print-summary ,n-abort-p *aborted-compilation-units*))))
  1697.        (let ((,n-abort-p t))
  1698.          (unwind-protect
  1699.          (multiple-value-prog1
  1700.              (,n-fun)
  1701.            (setq ,n-abort-p nil))
  1702.            (when ,n-abort-p
  1703.          (incf *aborted-compilation-units*))))))))
  1704.